package com.smarth.zhizulian.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.smarth.zhizulian.R;
import com.smarth.zhizulian.app.BaseActivity;
import com.smarth.zhizulian.app.BaseConfig;
import com.smarth.zhizulian.bean.BaseEntity;
import com.smarth.zhizulian.bean.login.Login;
import com.smarth.zhizulian.entity.EventBean;
import com.smarth.zhizulian.http.KumaHttp;
import com.smarth.zhizulian.http.observer.ProgressObserver;
import com.smarth.zhizulian.http.utils.OldDataUtils;
import com.smarth.zhizulian.http.utils.RxCompos;
import com.smarth.zhizulian.utils.CommonUtils;
import com.smarth.zhizulian.utils.KumaLog;
import com.smarth.zhizulian.utils.KumaToast;
import com.smarth.zhizulian.utils.SPUtils;
import com.smarth.zhizulian.utils.UserUtils;
import com.smarth.zhizulian.utils.ValidateUtils;

import org.simple.eventbus.EventBus;

import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import okhttp3.ResponseBody;

/**
 * Created by 18865 on 2017/12/22.
 */

public class LoginActivity extends BaseActivity {
    @BindView(R.id.ll_all)
    LinearLayout ll_all;
    @BindView(R.id.et_phone)
    EditText etPhone;
    @BindView(R.id.et_code)
    EditText etCode;
    @BindView(R.id.tv_getcode)
    TextView tvGetcode;
    @BindView(R.id.btn_login)
    Button btnLogin;
    @BindView(R.id.cb_checkbox)
    CheckBox cbCheckBox;
    private Disposable mDisposable;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
        setTitlebar("登录", true);
        initView();
    }

    private void initView() {
        btnLogin.setEnabled(false);
        etPhone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (!TextUtils.isEmpty(editable.toString())) {
                    btnLogin.setEnabled(true);
                } else {
                    btnLogin.setEnabled(false);
                }
            }
        });
        cbCheckBox.setChecked(true);
        cbCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b) {
                    if (!TextUtils.isEmpty(etPhone.getText().toString())) {
                        btnLogin.setEnabled(true);
                    }
                } else {
                    btnLogin.setEnabled(false);
                }
            }
        });
    }

    public static void open(Context context) {
        Intent i = new Intent(context, LoginActivity.class);
        context.startActivity(i);
    }

    public static void openForReLogin(Context context) {
        Intent i = new Intent(context, LoginActivity.class);
        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(i);
    }

    @OnClick({R.id.tv_getcode, R.id.btn_login, R.id.tv_agreement})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_getcode:
                fetchSMS();
                break;
            case R.id.btn_login:
                CommonUtils.hideKeyBoard(mContext, ll_all);
                fetchLogin();
                break;
            case R.id.tv_agreement:
//                AgreementActivity.open(mContext);
                AgentWebActivity.openForAgreement(mContext);
                break;
        }
    }

    private boolean isValidateGetCode() {
        String valPhone = ValidateUtils.valPhone(mContext, etPhone.getText().toString());
        if (!TextUtils.isEmpty(valPhone)) {
            KumaToast.show(mContext, valPhone);
            return false;
        }
        return true;
    }

    private boolean isValidateLogin() {
        String valPhone = ValidateUtils.valPhone(mContext, etPhone.getText().toString());
        if (!TextUtils.isEmpty(valPhone)) {
            KumaToast.show(mContext, valPhone);
            return false;
        }
        if (TextUtils.isEmpty(etCode.getText().toString())) {
            KumaToast.show(mContext, "请输入验证码");
            return false;
        }
        return true;
    }

    private void fetchSMS() {
        final int count = 60;
        KumaHttp.getService().loginSendValidateCode(etPhone.getText().toString())
                .compose(RxCompos.getBEAllCompos())
                .subscribe(new ProgressObserver<BaseEntity<Object>>(mContext, true) {
                    @Override
                    public void onNext(BaseEntity<Object> r) {
//                        KumaToast.test(mContext, "验证码：" + s);
                        Observable.interval(0, 1, TimeUnit.SECONDS)
                                .take(count + 1) //设置循环11次
                                .map(new Function<Long, Long>() {
                                    @Override
                                    public Long apply(@NonNull Long aLong) throws Exception {
                                        return count - aLong; //
                                    }
                                })
                                .doOnSubscribe(new Consumer<Disposable>() {
                                    @Override
                                    public void accept(Disposable disposable) throws Exception {
                                        tvGetcode.setEnabled(false);//在发送数据的时候设置为不能点击
                                    }
                                })
                                .observeOn(AndroidSchedulers.mainThread())//操作UI主要在UI线程
                                .subscribe(new Observer<Long>() {
                                    @Override
                                    public void onSubscribe(@NonNull Disposable d) {
                                        mDisposable = d;
                                    }

                                    @Override
                                    public void onNext(@NonNull Long aLong) {
//                                Log.d(TAG, "onNext: " + aLong);
                                        tvGetcode.setText(aLong + "秒后再获取");
                                        tvGetcode.setEnabled(false);
                                    }

                                    @Override
                                    public void onError(@NonNull Throwable e) {
                                        e.printStackTrace();
                                        tvGetcode.setText("获取验证码");//数据发送完后设置为原来的文字
                                        tvGetcode.setEnabled(true);
                                        KumaToast.showError(mContext, e.getMessage());
                                    }

                                    @Override
                                    public void onComplete() {
                                        tvGetcode.setText("获取验证码");//数据发送完后设置为原来的文字
                                        tvGetcode.setEnabled(true);
                                    }
                                });
                    }

                    @Override
                    public void onSubscribe(Disposable d) {
                        if (!isValidateGetCode()) {
                            d.dispose();
                            return;
                        }
                        super.onSubscribe(d);
                    }

                });
    }

    private void fetchLogin() {
        KumaHttp.getService().login(etPhone.getText().toString()
                , etCode.getText().toString()
                , CommonUtils.getAndroidID(mContext)
                , CommonUtils.getChannel(mContext))
                .compose(RxCompos.<Login>getBECompos())
                .subscribe(new ProgressObserver<Login>(mContext) {
                    @Override
                    public void onNext(@NonNull Login s) {
                        UserUtils.setToken(s.getToken());
                        EventBus.getDefault().post(new EventBean("用户进行了登录操作"), BaseConfig.EventTag.ON_LOGIN);
                        LoginActivity.this.finish();
                        if (!SPUtils.getBoolean(BaseConfig.SP.ONCE_LOGIN, false)) {
                            GuideActivity.open(mContext, s.getLoginType());
                            SPUtils.saveBoolean(BaseConfig.SP.ONCE_LOGIN, true);
                        }
                    }

                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        if (!isValidateLogin()) {
                            d.dispose();
                            return;
                        }
                        super.onSubscribe(d);
                    }
                });


    }

    @Override
    protected void onDestroy() {
        if (mDisposable != null && !mDisposable.isDisposed()) {
            KumaLog.kuma("mDisposable");
            mDisposable.dispose();
        }
        super.onDestroy();
    }

}
